<template>
  <div class="content-card">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑商品' : '添加商品' }}</h2>
    </div>
    
    <el-form 
      ref="formRef" 
      :model="formData" 
      :rules="rules" 
      label-width="100px"
      class="form-container"
    >
      <!-- 基本信息 -->
      <el-card class="form-section">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择商品分类">
            <el-option label="电子产品" value="1" />
            <el-option label="服装鞋帽" value="2" />
            <el-option label="家居用品" value="3" />
            <el-option label="美妆护肤" value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品品牌" prop="brandId">
          <el-select v-model="formData.brandId" placeholder="请选择商品品牌">
            <el-option label="品牌A" value="1" />
            <el-option label="品牌B" value="2" />
            <el-option label="品牌C" value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="formData.price" 
            placeholder="请输入商品价格"
            :min="0" 
            :precision="2"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="formData.stock" 
            placeholder="请输入商品库存"
            :min="0" 
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="formData.description" 
            placeholder="请输入商品描述"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-card>
      
      <!-- 商品状态 -->
      <el-card class="form-section">
        <template #header>
          <div class="card-header">
            <span>商品状态</span>
          </div>
        </template>
        
        <el-form-item label="上架状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>
      
      <!-- 表单操作 -->
      <div class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { reactive, ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productApi } from '../../api/product.js'

export default {
  name: 'ProductForm',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const formRef = ref(null)
    const loading = ref(false)
    
    // 判断是否为编辑模式
    const isEdit = computed(() => !!route.params.id)
    
    // 表单数据
    const formData = reactive({
      name: '',
      categoryId: '',
      brandId: '',
      price: 0,
      stock: 0,
      description: '',
      status: 1
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符之间', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
      ],
      brandId: [
        { required: true, message: '请选择商品品牌', trigger: 'change' }
      ],
      price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', min: 0, message: '商品价格不能小于0', trigger: 'blur' }
      ],
      stock: [
        { required: true, message: '请输入商品库存', trigger: 'blur' },
        { type: 'number', min: 0, message: '商品库存不能小于0', trigger: 'blur' }
      ],
      description: [
        { max: 200, message: '商品描述不能超过200个字符', trigger: 'blur' }
      ]
    }
    
    // 获取商品详情（编辑模式）
    const getProductDetail = async () => {
      if (isEdit.value) {
        loading.value = true
        try {
          // 模拟获取商品详情
          setTimeout(() => {
            // 模拟商品详情数据
            const mockProduct = {
              id: route.params.id,
              name: '测试商品',
              categoryId: '1',
              brandId: '2',
              price: 999.99,
              stock: 100,
              description: '这是一个测试商品的描述',
              status: 1
            }
            
            // 填充表单数据
            Object.assign(formData, mockProduct)
            loading.value = false
          }, 500)
          
          // 实际API调用代码（目前注释掉）
          // const response = await productApi.getProductDetail(route.params.id)
          // Object.assign(formData, response.data)
          // loading.value = false
        } catch (error) {
          console.error('获取商品详情失败:', error)
          ElMessage.error('获取商品详情失败')
          loading.value = false
        }
      }
    }
    
    // 处理表单提交
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        loading.value = true
        
        if (isEdit.value) {
          // 编辑商品
          // 模拟更新请求
          setTimeout(() => {
            ElMessage.success('商品更新成功')
            router.push('/product/list')
            loading.value = false
          }, 800)
          
          // 实际API调用代码（目前注释掉）
          // await productApi.updateProduct(formData)
          // ElMessage.success('商品更新成功')
          // router.push('/product/list')
          // loading.value = false
        } else {
          // 添加商品
          // 模拟添加请求
          setTimeout(() => {
            ElMessage.success('商品添加成功')
            router.push('/product/list')
            loading.value = false
          }, 800)
          
          // 实际API调用代码（目前注释掉）
          // await productApi.addProduct(formData)
          // ElMessage.success('商品添加成功')
          // router.push('/product/list')
          // loading.value = false
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        loading.value = false
      }
    }
    
    // 处理取消
    const handleCancel = () => {
      router.push('/product/list')
    }
    
    // 初始化数据
    onMounted(() => {
      getProductDetail()
    })
    
    return {
      formRef,
      loading,
      isEdit,
      formData,
      rules,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  margin-bottom: 20px;
}

.form-container {
  .form-section {
    margin-bottom: 20px;
    
    .card-header {
      font-weight: bold;
    }
  }
}

.form-actions {
  margin-top: 20px;
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}
</style>